package com.dz.lm.service;

import java.util.ArrayList;
import java.util.List;

import com.dz.lm.domain.moneybar.AgentNode;

import net.sf.json.JSONArray;

public class TreeBuilder {
	List<AgentNode> nodes = new ArrayList();

	public String buildTree(List<AgentNode> nodes) {
		TreeBuilder treeBuilder = new TreeBuilder(nodes);
		return treeBuilder.buildJSONTree();
	}

	public TreeBuilder() {
	}

	public TreeBuilder(List<AgentNode> nodes) {
		super();
		this.nodes = nodes;
	}

	// 构建JSON树形结构
	public String buildJSONTree() {
		List<AgentNode> nodeTree = buildTree();
		JSONArray jsonArray = JSONArray.fromObject(nodeTree);
		return jsonArray.toString();
	}

	// 构建树形结构
	public List<AgentNode> buildTree() {
		List<AgentNode> treeNodes = new ArrayList();
		List<AgentNode> rootNodes = getRootNodes();
		for (AgentNode rootNode : rootNodes) {
			buildChildNodes(rootNode);
			treeNodes.add(rootNode);
		}
		return treeNodes;
	}

	// 递归子节点
	public void buildChildNodes(AgentNode node) {
		List<AgentNode> children = getChildNodes(node);
		if (!children.isEmpty()) {
			for (AgentNode child : children) {
				buildChildNodes(child);
			}
			node.setChildren(children);
		}
	}

	// 获取父节点下所有的子节点
	public List<AgentNode> getChildNodes(AgentNode pnode) {
		List<AgentNode> childNodes = new ArrayList();
		for (AgentNode n : nodes) {
			if (pnode.getAgentProductId().equals(n.getOriginalProductId())) {
				childNodes.add(n);
			}
		}
		return childNodes;
	}

	// 判断是否为根节点
	public boolean rootNode(AgentNode node) {
		boolean isRootNode = true;
		for (AgentNode n : nodes) {
			if (node.getOriginalProductId().equals(n.getAgentProductId())) {
				isRootNode = false;
				break;
			}
		}
		return isRootNode;
	}

	// getPid == getOriginalProductId getId === getAgentProductId

	// 获取集合中所有的根节点
	public List<AgentNode> getRootNodes() {
		List<AgentNode> rootNodes = new ArrayList();
		for (AgentNode n : nodes) {
			if (rootNode(n)) {
				rootNodes.add(n);
			}
		}
		return rootNodes;
	}

}